package com.example.animdemo;

import android.app.Activity;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Debug;
import android.util.DisplayMetrics;
import android.view.KeyEvent;
import android.view.MotionEvent;
import com.example.animdemo.base.DebugLog;
import com.example.animdemo.game.Game;
import com.example.animdemo.render.GLSurfaceView;

public class AnimDemo extends Activity {
	public static final int VERSION = -1;
	private static final int ROLL_TO_FACE_BUTTON_DELAY = 400;
	private GLSurfaceView mGLSurfaceView;
    private Game mGame;
    private boolean mMethodTracing;
    
    private long mLastTouchTime = 0L;
    private long mLastRollTime = 0L;    
	
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        
        SharedPreferences prefs = getSharedPreferences(PreferenceConstants.PREFERENCE_NAME, MODE_PRIVATE);
        final boolean debugLogs = prefs.getBoolean(PreferenceConstants.PREFERENCE_ENABLE_DEBUG, false);
        
        if (debugLogs) {
        	DebugLog.setDebugLogging(true);
        } else {
        	DebugLog.setDebugLogging(false);
        }
        
        DebugLog.d("AnimDemo", "onCreate");
                
        
        setContentView(R.layout.activity_main);
        mGLSurfaceView = (GLSurfaceView) findViewById(R.id.glsurfaceview);
        
        mGLSurfaceView.setEGLConfigChooser(false);
        mGame = new Game();
        mGame.setSurfaceView(mGLSurfaceView);
        DisplayMetrics dm = new DisplayMetrics();
        getWindowManager().getDefaultDisplay().getMetrics(dm);
        
        int defaultWidth = 800;
        int defaultHeight = 480;
        if(dm.widthPixels != defaultWidth) {
        	float ratio = ((float)dm.widthPixels) / dm.heightPixels;
        	defaultWidth = (int)(defaultHeight * ratio);
        }
        
        
        mGame.bootstrap(this, dm.widthPixels, dm.heightPixels, defaultWidth, defaultHeight, 0 /*difficulty none*/);
        mGLSurfaceView.setRenderer(mGame.getRenderer());
    }

    @Override
    protected void onDestroy() {
    	DebugLog.d("AnimDemo", "onDestroy");
    	mGame.stop();
    	super.onDestroy();
    }

    @Override
    protected void onPause() {
        super.onPause();
        DebugLog.d("AnimDemo", "onPause");

        
        mGame.onPause();
        mGLSurfaceView.onPause();
        mGame.getRenderer().onPause();	// hack!
        
        if (mMethodTracing) {
            Debug.stopMethodTracing();
            mMethodTracing = false;
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        
        // Preferences may have changed while we were paused.
        SharedPreferences prefs = getSharedPreferences(PreferenceConstants.PREFERENCE_NAME, MODE_PRIVATE);
        final boolean debugLogs = prefs.getBoolean(PreferenceConstants.PREFERENCE_ENABLE_DEBUG, false);
        
        if (VERSION < 0 || debugLogs) {
        	DebugLog.setDebugLogging(true);
        } else {
        	DebugLog.setDebugLogging(false);
        }
        
        DebugLog.d("AnimDemo", "onResume");
        mGLSurfaceView.onResume();
        mGame.onResume(this, false);
    }

    @Override
    public boolean onTrackballEvent(MotionEvent event) {
    	if (!mGame.isPaused()) {
	        mGame.onTrackballEvent(event);
	        final long time = System.currentTimeMillis();
	        mLastRollTime = time;
    	}
        return true;
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
    	if (!mGame.isPaused()) {
    		mGame.onTouchEvent(event);
	    	
	        final long time = System.currentTimeMillis();
	        if (event.getAction() == MotionEvent.ACTION_MOVE && time - mLastTouchTime < 32) {
		        // Sleep so that the main thread doesn't get flooded with UI events.
		        try {
		            Thread.sleep(32);
		        } catch (InterruptedException e) {
		            // No big deal if this sleep is interrupted.
		        }
		        mGame.getRenderer().waitDrawingComplete();
	        }
	        mLastTouchTime = time;
    	}
        return true;
    }
    
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
    	boolean result = true;
    	if (keyCode == KeyEvent.KEYCODE_BACK) {
			final long time = System.currentTimeMillis();
    		if (time - mLastRollTime > ROLL_TO_FACE_BUTTON_DELAY &&
    				time - mLastTouchTime > ROLL_TO_FACE_BUTTON_DELAY) {
//    			showDialog(QUIT_GAME_DIALOG);
    			result = true;
    		}
    	} else if (keyCode == KeyEvent.KEYCODE_MENU) {
    		result = true;
    		if (mGame.isPaused()) {
//    			hidePauseMessage();
    			mGame.onResume(this, true);
    		} else {
    			final long time = System.currentTimeMillis();
    	        if (time - mLastRollTime > ROLL_TO_FACE_BUTTON_DELAY &&
    	        		time - mLastTouchTime > ROLL_TO_FACE_BUTTON_DELAY) {
//    	        	showPauseMessage();
    	        	mGame.onPause();
    	        }
    	        if (VERSION < 0) {
    	        	result = false;	// Allow the debug menu to come up in debug mode.
    	        }
    		}
    	} else {
		    result = mGame.onKeyDownEvent(keyCode);
		    // Sleep so that the main thread doesn't get flooded with UI events.
		    try {
		        Thread.sleep(4);
		    } catch (InterruptedException e) {
		        // No big deal if this sleep is interrupted.
		    }
    	}
        return result;
    }
     
    @Override
    public boolean onKeyUp(int keyCode, KeyEvent event) {
    	boolean result = false;
    	if (keyCode == KeyEvent.KEYCODE_BACK) {
    		result = true;
    	} else if (keyCode == KeyEvent.KEYCODE_MENU){ 
	        if (VERSION < 0) {
	        	result = false;	// Allow the debug menu to come up in debug mode.
	        }
    	} else {
    		result = mGame.onKeyUpEvent(keyCode);
	        // Sleep so that the main thread doesn't get flooded with UI events.
	        try {
	            Thread.sleep(4);
	        } catch (InterruptedException e) {
	            // No big deal if this sleep is interrupted.
	        }
    	}
        return result;
    }
}
